#include "GfxEntityModel.h"
#include "tools.h"

CGfxEntityModel::CGfxEntityModel(void):m_mesh(0), m_materialBuffer(0), m_numMaterials(0), m_d3dxMaterials(0), m_meshMaterials(0),
				m_meshTextures(0)			
{}

CGfxEntityModel::~CGfxEntityModel(void)
{
	m_mesh->Release();
	for(DWORD i=0; i<m_numMaterials; i++)//release the texture
	{
		if(m_meshTextures[i]!=0)
			m_meshTextures[i]->Release();
	}
	delete m_meshMaterials;
	delete m_meshTextures;
	
}

bool CGfxEntityModel::load(string filePath)
{
	HRESULT hr=D3DXLoadMeshFromX(filePath.c_str(), D3DXMESH_SYSTEMMEM, VIS->getDevice(), 0, &m_materialBuffer, 0, &m_numMaterials, &m_mesh);
	if(FAILED(hr))
		return false;
	
	m_d3dxMaterials = (D3DXMATERIAL*)m_materialBuffer->GetBufferPointer();
	m_meshMaterials = new D3DMATERIAL9[m_numMaterials];
	m_meshTextures = new LPDIRECT3DTEXTURE9[m_numMaterials];

	for(DWORD i=0; i<m_numMaterials; i++)
	{
		//copy the material
		m_meshMaterials[i] = m_d3dxMaterials[i].MatD3D;

		//set the ambient color for the material (D3DX does not do this)
		m_meshMaterials[i].Ambient = m_meshMaterials[i].Diffuse;

		//create the texture if it exists - it may not
		m_meshTextures[i] = 0;
		string path;
		string filename;
		SplitPath(filePath, path, filename);
		if(m_d3dxMaterials[i].pTextureFilename)
		{
			std::string fileName=m_d3dxMaterials[i].pTextureFilename;
			//SplitPath(fileName, path, fileName);
			std::string completePath=path;
			completePath.append("\\");
			completePath.append(fileName);
			hr=D3DXCreateTextureFromFile(VIS->getDevice(), completePath.c_str(), &m_meshTextures[i]);
			if(FAILED(hr))
				return false;
		}
	}
	//release the material buffer
	m_materialBuffer->Release();
	return true;
}

void CGfxEntityModel::doRender()
{

	for(DWORD i=0; i<m_numMaterials; i++)
	{
		//set the material and texture for this subset
		VIS->getDevice()->SetMaterial(&m_meshMaterials[i]);
		VIS->getDevice()->SetTexture(0, m_meshTextures[i]);

		//draw the mesh subset
		m_mesh->DrawSubset(i);
	}
}

LPD3DXMESH CGfxEntityModel::getMesh()
{
	return m_mesh;
}